<?php
// +----------------------------------------------------------------------
// | HkCms 单页模型
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2019 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------
namespace app\content\model;

use common\model\Model as CommModel;
use \app\content\validate\Page as PageV;

class Page extends CommModel {

    /**
     * 根据栏目ID获取内容
     * @param type $catid 栏目ID
     * @return boolean
     */
    public function getPage($catid) {
        if (empty($catid)) {
            return false;
        }
        $one = $this->where(array('catid' => $catid))->find();
        if (!empty($one)) {
            $one = $one->toArray();
        }
        return $one;
    }

    /**
     * 更新单页内容
     * @param type $post 表单数据
     * @return boolean
     */
    public function savePage($post) {

        if (empty($post)) {
            $this->error = '内容不能为空！';
            return false;
        }
        $data = $post['info'];
        //表单令牌
        // $data[C("TOKEN_NAME")] = $post[C("TOKEN_NAME")];
        $catid = $data['catid'];

        $validate = new PageV;

        //单页内容
        $info = $this->where(array('catid' => $catid))->find();

        if ($info) {

            unset($data['catid']);
            // 验证数据
            $check = $validate->scene('edit')->check($data);
        }else{

            $check = $validate->check($data);
        }

        $data['updatetime'] = time();
        
        if (!$check) {

            $this->error = $validate->getError();

            return false;
        }

        //取得标题颜色
        if (isset($post['style_color'])) {
            //颜色选择为隐藏域 在这里进行取值
            $data['style'] = $post['style_color'] ? strip_tags($post['style_color']) : '';
            //标题加粗等样式
            if (isset($post['style_font_weight'])) {
                $data['style'] = $data['style'] . ($post['style_font_weight'] ? ';' : '') . strip_tags($post['style_font_weight']);
            }
        }
        if ($info) {
            if ($this->where('catid',$catid)->update($data) !== false) {

                //更新附件状态，把相关附件和文章进行管理
                service("Attachment")->api_update('', 'catid-' . $catid, 1);
                return true;
            }
        } else {
            if ($this->create($data) !== false) {
                //更新附件状态，把相关附件和文章进行管理
                service("Attachment")->api_update('', 'catid-' . $catid, 1);
                return true;
            }
        }
        $this->error = '操作失败！';
        return false;
    }

}
